<template>
  <view class="container">
    <view class="form-group">
      <input v-model="username" placeholder="请输入用户名" />
    </view>

    <button @click="submitBooking">提交预约</button>
  </view>
</template>

<script>
import { getUserIdByUsername, addRelation } from '@/api/system/relation.js';

export default {
  data() {
    return {
      username: '',
      therapist: null,
      selectedDate: '',
      selectedTime: ''
    };
  },
  onLoad(options) {
    this.therapist = JSON.parse(options.therapist);
    this.selectedDate = options.selectedDate;
    this.selectedTime = options.selectedTime;
  },
  methods: {
    async submitBooking() {
      const { username, therapist, selectedDate, selectedTime } = this;

      if (!username.trim()) {
        uni.showToast({ title: '请输入用户名', icon: 'none' });
        return;
      }

      try {
        const res = await getUserIdByUsername(username);
        if (res.code === 200) {
          const userId = res.data;

          const bookingData = {
            userId,
            therapistId: therapist.id,
            selectedDate,
            selectedTime
          };

          const addRes = await addRelation(bookingData);

          if (addRes.code === 200) {
            uni.$emit('bookingConfirmed', bookingData);

            uni.showToast({ title: '预约成功', icon: 'success' });
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          } else {
            uni.showToast({ title: '预约失败，请重试', icon: 'none' });
          }
        } else {
          uni.showToast({ title: res.msg || '用户不存在', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '网络异常，请重试', icon: 'none' });
        console.error('预约请求异常:', error);
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 40rpx;
}
.form-group input {
  border: 1rpx solid #ccc;
  padding: 20rpx;
  margin-bottom: 40rpx;
  border-radius: 8rpx;
}
</style>